package com.itheima.reggie.controller;


import com.itheima.reggie.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.UUID;

@RestController
@RequestMapping("/common")
@Slf4j
public class CommonController {
    @Value("${reggie.path}")
    private String basePath;


    /**
     * 文件上传
     *
     * @param file
     * @return
     */
    @PostMapping("/upload")
    public R upload(MultipartFile file) {
        log.info("文件上传:{}", file);

        //1.获取原始文件名,从原始文件名中截取文件后缀
        String originalFilename = file.getOriginalFilename();
        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
        //2.生成新文件防止文件重名覆盖
        String fileName = UUID.randomUUID().toString() + suffix;

        //3.处理文件储存目录,如果不存在就创建
        File dir = new File(basePath);

        if (!dir.exists()) {
            dir.mkdirs();
        }
        //4.将文件储存在指定文件夹中---转存文件
        File targetFile = new File(basePath + fileName);

        try {
            file.transferTo(targetFile);
        } catch (IOException e) {
            e.printStackTrace();
            return R.error("上传失败");
        }
        return R.success(fileName);
    }


    @GetMapping("/download")
    public void download(String name, HttpServletResponse response) throws IOException {
        //1.锁定要下载的文件
        File file =new File(basePath + name);

        //2.通过输入流读取服务器上传文件
        FileInputStream inputStream = new FileInputStream(file);

        //3.通过输出流将文件写会客户端浏览器
        ServletOutputStream outputStream = response.getOutputStream();

        byte[] bytes = new byte[1024];
        int len = 0;

        //4.通过输入流,读对应的通过输出流写
        while ((len = inputStream.read(bytes)) !=-1){
            outputStream.write(bytes, 0, len);
        }

        //5.关闭资源
        outputStream.close();
        inputStream.close();

    }


}
